package config

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"log"
	"strings"
)

type Config struct {
	Name   string
	Active string
}

var configList []*Config
var v *viper.Viper

func Init() {

	active := Env.Active
	//log.Println("./config"+ active)
	cfg := &Config{Name: "./config", Active: active}
	e := cfg.InitConfig()
	if e != nil {
		configList = append(configList, cfg)
		//log.Println("./bin/config" + active)
		cfg := &Config{Name: "./bin/config", Active: active}
		e = cfg.InitConfig()
		if e != nil {
			configList = append(configList, cfg)
			fmt.Println(e)
			fmt.Println("加载配置文件失败，请检查目录是否放置正确，可以放根目录也可以放bin目录")
			return
		}
	}
	v = viper.GetViper()
}
func GetConfigList() []*Config {
	return configList
}
func V() *viper.Viper {

	return v
}

// 读取配置
func (c *Config) InitConfig() error {
	if c.Name != "" {
		viper.SetConfigFile(c.Name + ".yaml")
	} else {
		viper.AddConfigPath("config")
		viper.SetConfigName("config")
	}
	viper.SetConfigType("yaml")
	//fmt.Println(c.Name)
	// 从环境变量总读取
	viper.AutomaticEnv()
	viper.SetEnvPrefix("web")
	viper.SetEnvKeyReplacer(strings.NewReplacer("_", "."))
	log.Println("读取基础配置文件:", c.Name+".yaml")
	err := viper.ReadInConfig()
	if err != nil {
		return err
	} else {
		c.WatchConfig()
	}
	//// 合并另一个配置文件
	if c.Active != "" {
		err = c.MergeInConfig(c.Name + "-" + c.Active + ".yaml")
		if err != nil {
			return err
		} else {
			c.WatchConfig()
		}
	}

	// 打印合并后的配置
	//fmt.Println(viper.AllSettings())
	return nil
}
func (c *Config) MergeInConfig(file string) error {
	log.Println("读取合并配置文件:", file)
	viper.SetConfigFile(file)
	err := viper.MergeInConfig()
	if err != nil {
		log.Println("读取合并配置文件失败:", file)
		return err
	}
	//serverId := viper.GetString("gateway.server-id")
	//log.Println("配置文件serverId:", serverId)
	//gatewayProxy := viper.Get("gateway.proxy")
	//log.Println("配置文件gateway.proxy:",gatewayProxy)
	return err
}

// 监控配置改动
func (c *Config) WatchConfig() {
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		if e.Op&fsnotify.Write != 0 && len(viper.AllKeys()) > 0 {
			log.Printf("配置已经被改变: %s", e.Name)
			err := c.MergeInConfig(e.Name)
			if err != nil {
				return
			}
		}
	})
}
